import { useUserStore } from '@/store/modules/user/user';
import { likeVideoAPI, getVideoComment, commentVideoAPI, likeCommentAPI } from '@/api/home/Home';

export const useVideoInteractions = (options = {}) => {
  const { onClose = () => { }, onCommentSuccess = () => { } } = options;
  const userStore = useUserStore();

  // 评论区相关状态
  const showComment = ref(false);
  // 评论区视频数据
  const currentVideo = ref(null);
  // 当前视频ID（用于评论区）
  const commentVideoId = ref(null);
  // 评论内容
  const commentContent = ref('');

  // 检查登录状态（未登录则唤起登录）
  const checkLogin = () => {
    if (!userStore.checkLogin()) {
      userStore.showLogin();
      return false;
    }
    return true;
  };

  // 视频点赞逻辑
  const likeVideo = async (videoId, videoList, videoItemKey = 'video') => {
    console.log(videoList);

    if (!checkLogin()) return;

    try {
      const res = await likeVideoAPI(userStore.userInfo.userId, videoId);
      if (res.code === 200) {
        // 根据不同组件的数据结构，动态获取视频项（支持不同字段名）
        const videoItem = videoList.find(item => item[videoItemKey].videoId === videoId);
        // if (videoItem) {
        //   videoItem.isLiked = !videoItem.isLiked;
        //   videoItem.stats.likeNum = videoItem.isLiked
        //     ? videoItem.stats.likeNum + 1
        //     : videoItem.stats.likeNum - 1;
        // }ijj
        if (videoItemKey === 'video') {
          if (videoItem) {
            videoItem.isLiked = !videoItem.isLiked;
            videoItem.stats.likeNum = videoItem.isLiked
              ? videoItem.stats.likeNum + 1
              : videoItem.stats.likeNum - 1;
          }
        } else if (videoItemKey === 'Video') {
          console.log(videoItem);
          if (videoItem) {
            videoItem.isLiked = !videoItem.isLiked;
            videoItem.WSLCNum.likeNum = videoItem.isLiked
              ? Number(videoItem.WSLCNum.likeNum) + 1
              : Number(videoItem.WSLCNum.likeNum) - 1;
          }
        }
      }
    } catch (error) {
      console.error('视频点赞失败:', error);
    }
  };
  // 评论点赞逻辑
  const likeComment = async (videoId, commentId) => {

    try {
      const res = await likeCommentAPI(userStore.userInfo.userId, videoId, commentId);
      if (res.code === 200) {
        currentVideo.value.forEach(element => {
          if (element.Comment.commentId === commentId) {
            element.Comment.isLiked = !element.Comment.isLiked;
            element.likeNum = Number(element.likeNum);
            element.likeNum += element.Comment.isLiked ? 1 : -1;
          }
        });
      }
    } catch (error) {
      console.error('评论点赞失败:', error);
    }
  };

  // 打开评论区
  const openComment = async (videoId = commentVideoId.value) => {
    if (!checkLogin()) return;

    try {
      const res = await getVideoComment(videoId);
      if (res.code === 200) {
        showComment.value = true;
        console.log();
        
        currentVideo.value = res.data;
        commentVideoId.value = videoId;
      }
    } catch (error) {
      console.error('获取评论失败:', error);
    }
  };

  // 关闭评论区
  const closeComment = () => {
    onClose();
  };

  // 提交评论
  const submitComment = async (videoId) => {
    if (!commentContent.value.trim()) return;
    try {
      const res = await commentVideoAPI({
        fromUserId: userStore.userInfo.userId,
        replyId: '',
        content: commentContent.value,
        toVideoId: videoId
      });
      if (res.code === 200) {
        commentContent.value = '';
        // 重新获取评论列表
        onCommentSuccess();
        return true; // 评论成功
      }
    } catch (error) {
      console.error('提交评论失败:', error);
    }
    return false;
  };

  return {
    // 状态
    showComment,
    currentVideo,
    commentContent,
    // 方法
    likeVideo,
    openComment,
    closeComment,
    submitComment,
    likeComment
  };
};
